<!--
  * 云喇叭表单
-->
<template>
  <a-modal
    :title="formType == 'add' ? '绑定' : '修改'"
    :width="600"
    :open="visibleFlag"
    @cancel="onClose"
    :maskClosable="false"
    :destroyOnClose="true"
  >
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="绑定门店" name="storeName">
            <CustomSelect
              v-model:value="formData.storeName"
              :placeholder="'请选择门店'"
              queryParamKey="storeNameLeftLike"
              :api="storeApi.page"
              :initParams="{ no: formData.storeNo }"
              @change="(...data) => handleChangeStore(data)"
              label-field="storeName,id"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="绑定台卡" name="codeIds">
            <CustomSelect
              v-model:value="formData.codeIds"
              :placeholder="'请选择台卡'"
              queryParamKey="code"
              :api="codeApi.page"
              mode="multiple"
              :queryParams="queryParamsCode"
              :initParams="{ ids: formData.codeIds }"
              @change="(...data) => handleChangeCode(data)"
              label-field="code"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="props.formType === 'update'">
          <a-form-item name="dmdId">
            <template #label>
              播报模板

              <a-switch v-model:checked="formData.dmdStatus" :checkedValue="1" :unCheckedValue="0" class="m-l-3" v-if="cloudDevice == 1" />
            </template>
            <CustomSelect
              ref="dmdSelect"
              v-model:value="formData.dmdId"
              :placeholder="'请选择播报模板，不选择默认模板'"
              queryParamKey="name"
              :api="deviceModuleDetailApi.page"
              :queryParams="queryParamsDmd"
              :initParams="{ id: formData.dmdId }"
              @change="(...data) => handleChangeDmd(data)"
              label-field="name"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="props.formType === 'update'">
          <a-table size="small" :dataSource="dmdTable" :columns="columns" rowKey="id" bordered :pagination="false" :scroll="{ x: 'max-content' }" />
        </a-col>
        <a-col :span="24" v-if="props.formType === 'update' && cloudDevice == 1" class="m-t-6">
          <a-form-item name="printDmdId">
            <template #label>
              打印模板
              <a-switch v-model:checked="formData.printDmdStatus" :checkedValue="1" :unCheckedValue="0" class="m-l-3" v-if="cloudDevice == 1" />
            </template>
            <CustomSelect
              ref="printDmdSelect"
              v-model:value="formData.printDmdId"
              :placeholder="'请选择打印模板，不选择默认模板'"
              queryParamKey="name"
              :api="deviceModuleDetailApi.page"
              :queryParams="queryParamsPrintDmd"
              :initParams="{ id: formData.printDmdId }"
              @change="(...data) => handleChangeprintDmd(data)"
              label-field="name"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="props.formType === 'update' && cloudDevice == 1">
          <a-table
            size="small"
            :dataSource="printDmdTable"
            :columns="columns01"
            rowKey="id"
            bordered
            :pagination="false"
            :scroll="{ x: 'max-content' }"
          />
        </a-col>
      </a-row>
    </a-form>
    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
        <slot></slot>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { reactive, ref, nextTick, computed, watch } from 'vue'
  import _ from 'lodash'
  import { message } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { smartSentry } from '/@/lib/smart-sentry'
  import { deviceApi } from '/@/api/business/b-merchant/device'
  import { storeApi } from '/@/api/business/b-merchant/store/store-api'
  import { codeApi } from '/@/api/business/b-merchant/code/code-api'
  import { deviceModuleDetailApi } from '/@/api/business/b-merchant/device-module-detail'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { useRoute } from 'vue-router'
  const route = useRoute()
  // ---------------------------- 表格列 ----------------------------
  const cloudDevice = computed(() => {
    // 0云喇叭 1云打印
    return route.path.includes('cloud-speaker') ? 0 : 1
  })

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    // 表单类型 add/update/view
    // add: 新增, update: 编辑,view: 查看
    formType: {
      type: String,
      default: 'add',
    },
    rowData: {
      type: Object,
      default: () => {},
    },
  })

  const columns = ref([
    {
      title: '播报内容',
      dataIndex: 'content',
      width: 380,
      customRender: ({ record, text, index }) => {
        return text
      },
      ellipsis: true,
    },
    {
      title: '金额读取',
      dataIndex: 'retain',
      customRender: ({ text }) => {
        return text == 0 ? '小数后两位，遇0不可省' : '小数后两位，遇0可省'
      },
      ellipsis: true,
    },
  ])

  const columns01 = ref([
    {
      title: '打印内容',
      dataIndex: 'content',
      customRender: ({ record, text, index }) => {
        return text
      },
      ellipsis: true,
    },
  ])
  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['ok', 'update:open'])
  const visibleFlag = computed({ get: () => props.open, set: (val) => emits('update:open', val) })

  // ------------------------ 显示与隐藏 ------------------------
  function onClose() {
    Object.assign(formData.value, formDefault)
    visibleFlag.value = false
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }

  // ------------------------ 获取表单数据 ------------------------
  async function getFormData(data) {
    SmartLoading.show()
    try {
      let res = await deviceApi.findId(data)
      formData.value = { ...res.data }
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }
  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref()

  const formDefault = {
    storeName: undefined,
    storeNo: undefined,
    storeId: undefined,
    code: undefined,
    codeIds: undefined,
    dmdId: undefined,
    printDmdId: undefined,
    dmdStatus: 1,
    printDmdStatus: 1,
  }

  let formData = ref({ ...formDefault })

  const rules = {
    codeIds: [{ required: true, message: '绑定台卡 必填' }],
    storeName: [{ required: true, message: '绑定门店 必填' }],
  }

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields()
      save()
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!')
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show()
    try {
      // let data = { ...formData.value, ...props.rowData }
      // await deviceApi.broadcast(data)

      await codebindDevice()
      await deviceBindStore()
      await deviceUpdate()
      message.success('操作成功')
      emits('ok')
      onClose()
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }

  // 选择门店
  const handleChangeStore = (data) => {
    formData.value.codes = undefined
    formData.value.codeIds = undefined
    if (!data?.[1][0]) {
      formData.value.storeName = undefined
      formData.value.storeNo = undefined
      formData.value.storeId = undefined
      return
    }
    formData.value.storeName = data[1][0].storeName
    formData.value.storeNo = data[1][0].no
    formData.value.storeId = data[1][0].id
  }
  // 选择码牌
  const queryParamsCode = computed(() => {
    return {
      storeId: formData.value.storeId,
    }
  })
  const handleChangeCode = (data) => {
    console.log('选择码牌', data[1])

    if (!data?.[1][0]) {
      formData.value.codes = undefined
      formData.value.codeIds = undefined
      return
    }
    formData.value.codes = data[1].map((e) => e.code)
    // formData.value.codeIds = data[1].map((e) => e.id)
  }

  // 设备绑定台卡
  const codebindDevice = async () => {
    let params = { id: formData.value.codeIds, deviceId: props.rowData.id }
    let res = await codeApi.bindDevice(params)
    return res
  }
  // 设备绑定门店
  const deviceBindStore = async () => {
    let params = { id: props.rowData.id, storeId: formData.value.storeId, storeName: formData.value.storeName }
    let res = await deviceApi.bindStore(params)
    return res
  }
  // 设备绑定模板
  const dmdSelect = ref()
  const queryParamsDmd = computed(() => {
    return {
      deviceId: props.rowData.id,
      deviceType: 0,
    }
  })
  // 选择播报模板
  const handleChangeDmd = (data) => {
    console.log('选择模板', data[1])
    // formData.value.codeIds = data[1].map((e) => e.id)
  }
  const dmdTable = computed(() => {
    let data = []
    if (dmdSelect.value?.getSelectedOptions.length > 0) {
      data = dmdSelect.value?.getSelectedOptions
    } else if (dmdSelect.value?.options) {
      data = dmdSelect.value?.options.filter((e) => e.isDefault == 1)
    }
    return data
  })
  // 设备绑定打印模板
  const printDmdSelect = ref()
  const queryParamsPrintDmd = computed(() => {
    return {
      deviceId: props.rowData.id,
      deviceType: 1,
    }
  })
  // 选择播报模板
  const handleChangeprintDmd = (data) => {
    console.log('选择模板', data[1])

    if (!data?.[1][0]) {
      formData.value.codes = undefined
      formData.value.codeIds = undefined
      return
    }
    formData.value.codes = data[1].map((e) => e.code)
    // formData.value.codeIds = data[1].map((e) => e.id)
  }
  const printDmdTable = computed(() => {
    let data = []
    if (printDmdSelect.value?.getSelectedOptions.length > 0) {
      data = printDmdSelect.value?.getSelectedOptions
    } else if (printDmdSelect.value?.options) {
      data = printDmdSelect.value?.options.filter((e) => e.isDefault == 1)
    }
    return data
  })
  const deviceUpdate = async () => {
    let params = {
      id: props.rowData.id,
      dmdId: formData.value.dmdId,
      dmdStatus: formData.value.dmdStatus,
      printDmdId: formData.value.printDmdId,
      printDmdStatus: formData.value.printDmdStatus,
    }
    let res = await deviceApi.update(params)
    return res
  }

  watch(
    [() => props.rowData, () => props.open],
    (val) => {
      if (props.open && props.rowData && props.formType != 'add') {
        let data = { id: props.rowData.id }
        getFormData(data)
      }
    },
    { immediate: true },
  )
</script>
